package com.wdd.myplatform.filter;

import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 设置skywalking的traceId到response请求头
 *
 * @author
 */
@ConditionalOnProperty(value = "skywalking.switch", havingValue = "true", matchIfMissing = false)
@Component
public class TraceResponseFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        try{
            //设置skywalking的traceId
            httpServletResponse.addHeader("traceId", TraceContext.traceId());
        }catch (Exception e){}

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}
